$(function () {


    var config = {
        coloum_num: 3, //列数目
        query: '/info/query?',//分页查询URL,
        create: '/info/create',//create,
        update: '/info/update',
        get: '/info/get',
        'delete': '/info/delete',
    };
    var query = {}, fields = 'id|title|summary',
        $search = $('.search'), $searchBar = $('.search-btn');
    var self = this;
    window.editor = UE.getEditor('validate-content', {
        //工具栏
        toolbars: [[
            'fullscreen', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'strikethrough', , 'removeformat', 'formatmatch',
            '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'link', 'unlink', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
            'insertframe', '|',
            'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload',
            'horizontal',
        ]]
        , lang: "zh-cn"
        //字体
        , 'fontfamily': [
            {label: '', name: 'songti', val: '宋体,SimSun'},
            {label: '', name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
            {label: '', name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
            {label: '', name: 'heiti', val: '黑体, SimHei'},
            {label: '', name: 'lishu', val: '隶书, SimLi'},
            {label: '', name: 'andaleMono', val: 'andale mono'},
            {label: '', name: 'arial', val: 'arial, helvetica,sans-serif'},
            {label: '', name: 'arialBlack', val: 'arial black,avant garde'},
            {label: '', name: 'comicSansMs', val: 'comic sans ms'},
            {label: '', name: 'impact', val: 'impact,chicago'},
            {label: '', name: 'timesNewRoman', val: 'times new roman'}
        ]
        //字号
        , 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
        , enableAutoSave: false
        , autoHeightEnabled: false
        , initialFrameHeight: '400px'
        , initialFrameWidth: '100%'
        , readonly: false
        , whitList: {
            a: ['target', 'href', 'title', 'class', 'style'],
            abbr: ['title', 'class', 'style'],
            address: ['class', 'style'],
            area: ['shape', 'coords', 'href', 'alt'],
            article: [],
            aside: [],
            audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'],
            b: ['class', 'style'],
            bdi: ['dir'],
            bdo: ['dir'],
            big: [],
            blockquote: ['cite', 'class', 'style'],
            br: [],
            caption: ['class', 'style'],
            center: [],
            cite: [],
            code: ['class', 'style'],
            col: ['align', 'valign', 'span', 'width', 'class', 'style'],
            colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'],
            dd: ['class', 'style'],
            del: ['datetime'],
            details: ['open'],
            div: ['class', 'style'],
            dl: ['class', 'style'],
            dt: ['class', 'style'],
            em: ['class', 'style'],
            font: ['color', 'size', 'face'],
            footer: [],
            h1: ['class', 'style'],
            h2: ['class', 'style'],
            h3: ['class', 'style'],
            h4: ['class', 'style'],
            h5: ['class', 'style'],
            h6: ['class', 'style'],
            header: [],
            hr: [],
            i: ['class', 'style'],
            img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', '_url', 'loadingclass', 'class', 'data-latex'],
            ins: ['datetime'],
            li: ['class', 'style'],
            mark: [],
            nav: [],
            ol: ['class', 'style'],
            p: ['class', 'style'],
            pre: ['class', 'style'],
            s: [],
            section: [],
            small: [],
            span: ['class', 'style'],
            sub: ['class', 'style'],
            sup: ['class', 'style'],
            strong: ['class', 'style'],
            table: ['width', 'border', 'align', 'valign', 'class', 'style'],
            tbody: ['align', 'valign', 'class', 'style'],
            td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
            tfoot: ['align', 'valign', 'class', 'style'],
            th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
            thead: ['align', 'valign', 'class', 'style'],
            tr: ['rowspan', 'align', 'valign', 'class', 'style'],
            tt: [],
            u: [],
            ul: ['class', 'style'],
            video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style'],
            source: ['src', 'type'],
            // embed:['type','class','pluginspage','src','wdith','height','align','style','wmode','play','autoplay',
            //     'loop','menu','allowsscriptaccess','allowfullscreen','controls','preload'
            // ],
            iframe: ['src', 'class', 'height', 'width', 'max-width', 'max-height', 'align',
                'frameborder', 'allowfullscreen'
            ]
        }
    });
    window.editor.ready(function (ueditor) {
        var search = parseSearch();
        var self = this;
        if (search && search.id && (search.id + '').length) {
            if (search.id == 0 || search.id) {
                $.get(config.get + '?id=' + search.id, function (data) {
                    if (data.code == 200) {
                        data = data.data;
                        Object.keys(data).map(function (item, index) {
                            if (item == 'thumbnail') {
                                $('[name=thumbnail1]').attr('src', data[item])
                            }
                            $('[name=' + item + ']').val(data[item]);
                            if (item == 'tags') {
                                $('input[name=tags]').tagsinput();
                            }
                            if (item == 'categoryId') {
                                setCategoryId(data[item]);
                            }
                        });
                        self.setContent(data.content.index('%3D')>-1?unescape(data.content):data.content);
                    }
                })
            }
        } else {
            $('input[name=tags]').tagsinput();
            setCategoryId();
        }
        onClick($('.save-upload'), function () {
            var path_ = '';
            var $index = dialogForm(
                {
                    width: '100%',
                    fullScreen: true,
                    data: [
                        {
                            type: 'upload-btn',
                            label: '上级菜单',
                            require: true, // 是否必填
                            name: 'upload',
                            previewClass: 'upload-preview'
                        },
                    ],
                    shown: function (obj) {
                        $('#dialog-form [type=submit]').hide();// 隐藏
                        $('.upload-select').$upload({
                            w: 185,
                            h: 164,
                            previewClass: 'upload-preview',
                            submit: function (path) {
                                $('.upload-preview').attr('src', path);
                                path_ = path;
                                // $('[name=thumbnail1]').attr('src', path);
                                // $('[name=thumbnail]').val(path);
                            }
                        })
                    },
                    submit: function (form) {
                        debugger;
                        closeLayer($index);
                        $('[name=thumbnail1]').attr('src', path);
                        $('[name=thumbnail]').val(path);
                    }
                });
        });
        $('[name=tags]').keydown(function (event) {
            if (event.keyCode == 13) {
                event.stopPropagation();
                event.preventDefault();
                //submitForm();
            }
        });

    });
    function setCategoryId(selected) {
        selectGoods({
            placeholder: '选择分类',
            name: 'categoryId',
            url: '/category/list?type1=info',
            selected: selected,
            key: 'inf-category',
            change: function () {

            }
        })
    }

    var content_ = "";

    window.editor.addListener('contentChange', function (editor_) {
        var self = this;
        content_ = self.getContent();
    });
    var $submit = $('#submit');
    $("#user-form").submit(function (e) {
        e.preventDefault();
        e.stopPropagation();

        debugger;
        $submit.button('loading');
        var form = decodeObj(parseSearch($('#user-form').serialize()))
        if (!form['title']) {
            $submit.button('reset');
            return fnFail('请填写标题!')
        }
        if (!form['thumbnail']) {
            $submit.button('reset');
            return fnFail('请上传缩略图!')
        }
        if (!form['tags']) {
            $submit.button('reset');
            return fnFail('请输入关键字!')
        }
        if (!form['summary']) {
            $submit.button('reset');
            return fnFail('请填写摘要!')
        }
        if (form['summary'].length > 250) {
            $submit.button('reset');
            return fnFail('摘要信息不能超过250个字符!')
        }
        content_ = window.editor.getContent();
        if (!content_.length) {
            $submit.button('reset');
            return fnFail('请填写正文内容!')
        }
        form.content = content_;
        var url = config.create;
        if (parseSearch().id) { // is update?
            form.id = parseSearch().id;
            url = config.update;
        } else {
            delete form.id;
        }
        if (!form.title) {
            return alert('请输入标题!')
        }
        $.post(url, form, function (xhr, data) {
            if (xhr.code == 200) {
                fnSuccess('发布成功!');
                window.location.href = './index.html';
            } else {
                fnFail(xhr.error)
            }
            $submit.button('reset');
        });
        return false;

    });


});